package com.commerce.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.commerce.common.entity.Favorite;
import com.commerce.common.entity.Product;
import com.commerce.common.utils.PageResult;
import com.commerce.user.feign.ProductFeignClient;
import com.commerce.user.mapper.FavoriteMapper;
import com.commerce.user.service.FavoriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收藏夹服务实现
 */
@Slf4j
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {

    @Autowired(required = false)
    private ProductFeignClient productFeignClient;

    @Override
    public boolean addFavorite(Long userId, Long productId) {
        // 检查是否已经收藏
        LambdaQueryWrapper<Favorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorite::getUserId, userId)
                   .eq(Favorite::getProductId, productId);
        
        Favorite existingFavorite = getOne(queryWrapper);
        if (existingFavorite != null) {
            log.warn("商品已在收藏夹中: userId={}, productId={}", userId, productId);
            return false;
        }

        // 创建新收藏记录
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setProductId(productId);
        favorite.setCreateTime(LocalDateTime.now());

        return save(favorite);
    }

    @Override
    public PageResult<Map<String, Object>> getUserFavorites(Long userId, int page, int size) {
        Page<Favorite> pageParam = new Page<>(page, size);

        LambdaQueryWrapper<Favorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorite::getUserId, userId)
                   .orderByDesc(Favorite::getCreateTime);

        Page<Favorite> resultPage = page(pageParam, queryWrapper);

        // 获取商品ID列表
        List<Long> productIds = resultPage.getRecords().stream()
                .map(Favorite::getProductId)
                .collect(java.util.stream.Collectors.toList());

        // 批量获取商品信息
        Map<Long, Product> productMap = new HashMap<>();
        if (!productIds.isEmpty() && productFeignClient != null) {
            try {
                com.commerce.common.utils.Result<List<Product>> productResult =
                    productFeignClient.getProductsByIds(productIds);
                if (productResult != null && productResult.isSuccess() && productResult.getData() != null) {
                    productResult.getData().forEach(product ->
                        productMap.put(product.getId(), product));
                }
            } catch (Exception e) {
                log.warn("获取商品信息失败，将返回不包含商品详情的收藏列表: {}", e.getMessage());
                // 继续执行，但不包含商品详情
            }
        } else if (productFeignClient == null) {
            log.warn("ProductFeignClient未初始化，将返回不包含商品详情的收藏列表");
        }

        // 组装返回数据
        List<Map<String, Object>> favoriteList = new ArrayList<>();
        for (Favorite favorite : resultPage.getRecords()) {
            Map<String, Object> favoriteItem = new HashMap<>();
            favoriteItem.put("id", favorite.getId());
            favoriteItem.put("userId", favorite.getUserId());
            favoriteItem.put("productId", favorite.getProductId());
            favoriteItem.put("createTime", favorite.getCreateTime());

            // 添加商品信息
            Product product = productMap.get(favorite.getProductId());
            if (product != null) {
                favoriteItem.put("name", product.getName());
                favoriteItem.put("price", product.getPrice());
                favoriteItem.put("originalPrice", product.getOriginalPrice());
                favoriteItem.put("mainImage", product.getMainImage());
                favoriteItem.put("stock", product.getStock());
                favoriteItem.put("sales", product.getSales());
            } else {
                // 如果没有商品信息，提供默认值
                favoriteItem.put("name", "商品信息加载中...");
                favoriteItem.put("price", 0);
                favoriteItem.put("originalPrice", 0);
                favoriteItem.put("mainImage", "");
                favoriteItem.put("stock", 0);
                favoriteItem.put("sales", 0);
            }

            favoriteList.add(favoriteItem);
        }

        return new PageResult<>(resultPage.getTotal(), favoriteList);
    }

    @Override
    public boolean checkFavorite(Long userId, Long productId) {
        LambdaQueryWrapper<Favorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorite::getUserId, userId)
                   .eq(Favorite::getProductId, productId);
        
        return count(queryWrapper) > 0;
    }

    @Override
    public boolean toggleFavorite(Long userId, Long productId) {
        LambdaQueryWrapper<Favorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorite::getUserId, userId)
                   .eq(Favorite::getProductId, productId);

        Favorite existingFavorite = getOne(queryWrapper);

        if (existingFavorite != null) {
            // 如果已收藏，则删除，返回false表示取消收藏
            removeById(existingFavorite.getId());
            return false;
        } else {
            // 如果未收藏，则添加，返回true表示已收藏
            addFavorite(userId, productId);
            return true;
        }
    }

    @Override
    public boolean removeFavoriteByProductId(Long productId) {
        LambdaQueryWrapper<Favorite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Favorite::getProductId, productId);

        return remove(queryWrapper);
    }
}
